<?php
/**
 * Created by PhpStorm.
 * User: bimcc-lw
 * Date: 2018/3/9
 * Time: 14:39
 */

namespace App\Models;

use Zizaco\Entrust\EntrustPermission;

class Permission extends EntrustPermission
{
    protected $fillable = [
        'name', 'display_name', 'menu_id', 'description'
    ];


    public function childPermission()
    {
        return $this->hasMany(config('entrust.permission'), 'pid', 'id');
    }

    public function allChildrenPermission()
    {
        return $this->childPermission();
    }

    static public function formatPermission($permissiontree)
    {
        foreach ($permissiontree as $item => $permission) {
            $permissiontree[$item]['icon'] = 'fa ' . $permission['icon'];
            foreach ($permission['all_children_permission'] as $key => $val) {
                $permissiontree[$item]['children'][$key]['id'] = $val['id'];
                $permissiontree[$item]['children'][$key]['text'] = $val['display_name'];
                $permissiontree[$item]['children'][$key]['icon'] = 'fa ' . $val['icon'];
                if ($val['name']) {
                    $permissiontree[$item]['children'][$key]['url'] = route($val['name']);
                } else {
                    $permissiontree[$item]['children'][$key]['url'] = '';
                }
                $permissiontree[$item]['children'][$key]['targetType'] = "iframe-tab";
                unset($permissiontree[$item]['all_children_permission']);
            }
        }
        return $permissiontree;
    }

    /**
     * @param $arr 菜单数据
     * @param int 父id
     * @param int 步进值
     * @param int 最大步进值
     * @return array|bool
     */
    static public function getPermissionTree($arr, $pid = 0, $step = 0, $maxstep = 2)
    {
        global $tree;

        if ($step >= $maxstep) {
            return true;
        }

        foreach ($arr as $key => $val) {
            if ($val['pid'] == $pid) {
                $flg = str_repeat('└―', $step);
                $val['display_name'] = $flg . $val['display_name'];
                $tree[] = $val;
                self::getPermissionTree($arr, $val['id'], $step + 1, $maxstep);
            }
        }
        return $tree;
    }
}